/*******************************************************************************
 * Package: com.song.common.config
 * Type:    CurrentLimiter
 * Date:    2024-01-07 13:19
 *
 * Copyright (c) 2024 LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.common.util;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

/**
 * 功能描述： redis 结合lua脚本实现接口限流
 *
 * @author Songxianyang
 * @date 2024-01-07 13:19
 */
@Component
@Slf4j
public class CurrentLimiterUtil {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisScript<Boolean> rateLimitLua;

    public void limitAccess(String key, Integer limit) {
        boolean acquired = stringRedisTemplate.execute(
                // Lua script的
                rateLimitLua,
                // Lua脚本中的Key列表
                Lists.newArrayList(key),
                // Lua脚本Value列表
                limit.toString()
        );

        if (!acquired) {
            log.error("您的访问被阻止, key={}", key);
            throw new RuntimeException("请勿重复访问！该接口被限流");
        }
    }
}
